/**
 * Created by Winter on 2016/5/10.
 */
TrafficeHistory = function() {

    this.config = {
        limit: 6,
        storageKey: 'TrafficeHistory',
        primaryKey: 'chepai'
    };

    this.cache = {
        localStorage: null,
        chepai: null
    };
};

TrafficeHistory.prototype = {

    init: function(config) {
        this.config = config || this.config;

        // define localStorage
        this.cache.localStorage = window.localStorage;
    },

    addHistory: function(item) {
        var items = this.getHistories();
        for (var i = 0, len = items.length; i < len; i++) {
            if (item[this.config.primaryKey] && items[i][this.config.primaryKey]
                && item[this.config.primaryKey] === items[i][this.config.primaryKey]) {
                items.splice(i, 1);
                break;
            }
        }

        items.push(item);

        if (this.config.limit > 0 && items.length > this.config.limit) {
            items.splice(0, 1);
        }

        var json = JSON.stringify(items);
        this.cache.localStorage.setItem(this.config.storageKey, json);
    },

    getHistories: function() {
        var history = this.cache.localStorage.getItem(this.config.storageKey);
        if (history) {
            return JSON.parse(history);
        }
        return [];
    },

    removeHistory: function(item) {
        var items = this.getHistories();
        for (var i = 0, len = items.length; i < len; i++) {
            if (item[this.config.primaryKey] && items[i][this.config.primaryKey]
                && item[this.config.primaryKey] === items[i][this.config.primaryKey]) {
                items.splice(i, 1);
                break;
            }
        }
        var json = JSON.stringify(items);
        this.cache.localStorage.setItem(this.config.storageKey, json);
    }
};